<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="音乐名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入音乐名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="artist">
        <el-input
          v-model="queryParams.artist"
          placeholder="请输入作者"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="歌曲来源" prop="url">
        <el-input
          v-model="queryParams.url"
          placeholder="请输入歌曲来源"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="歌曲封面" prop="cover">
        <el-input
          v-model="queryParams.cover"
          placeholder="请输入歌曲封面"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="歌词" prop="lrc">
        <el-input
          v-model="queryParams.lrc"
          placeholder="请输入歌词"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:music:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:music:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:music:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:music:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="musicList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="true"/>
      <el-table-column label="音乐名称" align="center" prop="name" />
      <el-table-column label="作者" align="center" prop="artist" />
      <el-table-column label="歌曲" align="center" prop="url">
        <template slot-scope="scope">
          <i
            style="
                cursor: pointer;
                margin-right: 10px;
                margin-top: 3px;
                font-size: 25px;
              "
            v-if="scope.row.url"
            @click="play(scope.$index, scope.row)"
            :class="icon == scope.row.url
                  ? 'el-icon-video-pause'
                  : 'el-icon-video-play'
              "
            :style="icon == scope.row.url ? 'color: red;' : ''"
          >
            <audio :id="scope.row.url">
              <source :src="scope.row.url" type="audio/mpeg" /></audio
            ></i>
          <div v-else>暂无音频</div>
        </template>
      </el-table-column>
      <el-table-column label="歌曲封面" align="center" prop="cover">
        <template slot-scope="scope">
          <el-image
            style="width: 70px; height: 70px;"
            :src="scope.row.cover"
            :preview-src-list="[scope.row.cover]"/>
        </template>
      </el-table-column>
      <el-table-column label="歌词" align="center" prop="lrc" width="200" show-overflow-tooltip/>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:music:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:music:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改音乐对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col>
            <el-form-item label="音乐名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入音乐名称" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="作者" prop="artist">
              <el-input v-model="form.artist" placeholder="请输入作者" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col>
            <el-form-item label="歌曲来源" prop="url">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleFile"
              >上传歌曲</el-button>
              <el-input v-model="form.url" placeholder="请输入歌曲来源" maxlength="255"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="歌曲封面" prop="cover">
            <el-col :span="4">
              <el-image
                style="width: 80px; height: 80px;"
                :src="form.cover"
                :preview-src-list="[form.cover]"/>
            </el-col>
            <el-col :span="5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleImage"
              >上传封面</el-button>
            </el-col>
              <el-input v-model="form.cover" placeholder="请输入歌曲封面" maxlength="255"/>
          </el-form-item>
        </el-row>
        <el-form-item label="歌词" prop="lrc">
          <el-input v-model="form.lrc" type="textarea" placeholder="请输入内容" maxlength="8000"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog :title="picTitle" :visible.sync="picOpen" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="picForm" :model="picForm" :rules="picRules" label-width="80px">
        <el-form-item label="文件名">
          <fileUpload v-model="picForm.file" :fileSize="40" :fileType="['mp3','flac']" v-if="type === 0" @input="getUploadFileList"/>
          <imageUpload v-model="picForm.file" v-if="type === 1" @input="getUploadPicFileList" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonPicLoading" type="primary" @click="picSubmitForm(type)">确 定</el-button>
        <el-button @click="picCancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { listMusic, getMusic, delMusic, addMusic, updateMusic,changeMusicStatus } from "@/api/essay/music";

export default {
  name: "Music",
  data() {
    return {
      // 按钮loading
      buttonLoading: false,
      buttonPicLoading:false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 音乐表格数据
      musicList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 视频播放
      audio: "",
      icon: "el-icon-video-play",
      //图片
      picTitle:"",
      picOpen:false,
      picForm:{},
      uploadPicFileList: '',
      uploadFileList: '',
      type: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: undefined,
        name: undefined,
        artist: undefined,
        url: undefined,
        cover: undefined,
        lrc: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "音乐名称不能为空", trigger: "blur" }
        ],
        artist: [
          { required: true, message: "作者不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "歌曲来源不能为空", trigger: "blur" }
        ]
      },
      // 表单校验
      picRules: {
        file: [
          { required: true, message: "文件不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询音乐列表 */
    getList() {
      this.loading = true;
      listMusic(this.queryParams).then(response => {
        this.musicList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        status: "0",
        name: undefined,
        artist: undefined,
        url: undefined,
        cover: undefined,
        lrc: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加音乐";
      this.uploadPicFileList = '';
      this.uploadFileList = '';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getMusic(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改音乐";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateMusic(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addMusic(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除音乐编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delMusic(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/music/export', {
        ...this.queryParams
      }, `music_${new Date().getTime()}.xlsx`)
    },
    /**
     * 状态修改
     * @param row
     */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.name + '"吗？').then(function() {
        return changeMusicStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 上传图片 */
    handleImage(){
      this.picOpen = true;
      this.picTitle = "上传图片";
      this.type = 1;
    },
    /** 文件按钮操作 */
    handleFile() {
      this.picOpen = true;
      this.picTitle = "上传文件";
      this.type = 0;
    },
    /** 提交按钮 */
    picSubmitForm(type) {
      this.picOpen = false;
      this.$refs["picForm"].validate(valid => {
        if (valid && type === 1) {
          this.buttonPicLoading = true
          this.form.cover = this.uploadPicFileList
          this.buttonPicLoading = false
          this.picOpen = false
        }else {
          this.buttonPicLoading = true
          this.form.url = this.uploadFileList
          this.buttonPicLoading = false
          this.picOpen = false
        }
        this.getList();
      });

    },
    picCancel(){
      this.picOpen = false;
    },
    getUploadPicFileList(data) {
      this.uploadPicFileList = data
    },
    getUploadFileList(data) {
      this.uploadFileList = data
    },

    /**
     * 播放歌曲
     * @param index
     * @param row
     */
    play(index, row) {
      if (
        this.audio !== "" &&
        this.audio !== document.getElementById(row.url)
      ) {
        this.audio.pause();
      }
      this.audio = document.getElementById(row.url);
      this.icon = row.url;
      if (this.audio.paused) {
        this.audio.play();
        this.icon= row.url
      } else {
        this.icon = ""
        this.audio.pause();
      }
    }
  }
};
</script>
